//
//  IFMySchedulingManagerVC.m
//  Medicare
//
//  Created by admin on 2017/8/7.
//  Copyright © 2017年 medicare. All rights reserved.
//

//
//  ZScheduleViewController.m
//  Medicare
//
//  Created by jiezheng on 2017/7/3.
//  Copyright © 2017年 medicare. All rights reserved.
//

#import "IFMySchedulingManagerVC.h"
#import "FSCalendarScopeHandle.h"
#import "FSCalendar.h"
#import <EventKit/EventKit.h>
#import "UIView+FitScale.h"
#import "MainTopButton.h"
#import "MJRefresh.h"
#import "QJScheduleModel.h"

#import "UITableView+CustomReload.h"
#import "UIView+AddLine.h"
#import "SBPickerSelector.h"
#import "IFMySchedulCell.h"
#import "IFScheduStateView.h"
#import "IFSchedulTimeView.h"
#import "IFSchedulAddButton.h"
#import "IFNewPatientRoundsTwoCell.h"
#import "IFSchedulDocPersonModel.h"
#import "IFSchedulDocListModel.h"
#import "IFSchedulDocModel.h"
#import "ZSchedulingTypeModel.h"
#import "ZAddSchedulingViewController.h"
#import "IFAddScheduingPersonVC.h"
#import "IFMySchedulingPublicDefines.h"

#define CALENDAR_HEIGHT 300
#define SCHEDULE_BOTTOM_HEIGHT 60
#define WEEKS_COUNT 7
#define SELECTED_TODAY_COLOR [UIColor colorWithHexString:@"01C0FD"]
#define SELECTED_OTHERDAY_COLOR [UIColor colorWithHexString:@"4D4D4D"]

#define SELECTED_EVENT_COLOR [UIColor colorWithHexString:@"FF9B0B"]
static const NSInteger voiceBarHeight = 125;
@interface IFMySchedulingManagerVC ()<UITableViewDataSource,UITableViewDelegate,FSCalendarDataSource,FSCalendarDelegate,UIGestureRecognizerDelegate,SBPickerSelectorDelegate,IFMySchedulCellDelegate,IFScheduSchedulTimeViewDelegate,IFAddScheduingPersonDelegate,ZAddSchedulingClassDelegate>{
    void * _KVOContext;
}
@property (strong, nonatomic) FSCalendar *calendar;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSDateFormatter *dateFormatter;
@property (strong, nonatomic) UIPanGestureRecognizer *scopeGesture;
@property (strong, nonatomic) NSCalendar *gregorianCalendar;
@property (strong, nonatomic) NSCalendar *chineseCalendar;
@property (strong, nonatomic) NSArray<EKEvent *> *events;
@property (strong, nonatomic) NSArray<NSString *> *lunarChars;
@property (strong, nonatomic) MainTopButton *monthTitle;//月份选择按钮
@property (strong, nonatomic) IFLYBackButton *addButton;//编辑按钮
@property (strong, nonatomic) NSMutableArray *dataArray;//数据源
//@property (assign, nonatomic) NSInteger selectNumber;//当前已选中数字
@property (strong, nonatomic) SBPickerSelector *datePicker;
@property (strong,nonatomic) IFSchedulTimeView * bottomTimeView;
@property (strong,nonatomic) NSMutableArray * selectStateViewArray; //用来存放未排好班的view
@property (strong,nonatomic) NSMutableArray * selectLinedUpClassArray; //用来存放已经排好班的view
@property (strong,nonatomic) IFSchedulAddButton * addSchedulBtn;
@property (strong,nonatomic) UIButton * LastWeekCopyBtn;
@property (assign,nonatomic) BOOL isClickSchedul;//用来记录是否选择了班次
@property (strong,nonatomic)NSMutableArray *dataSourArray;//数据源数组
@property (assign,nonatomic) NSInteger pageNum;
@property (strong,nonatomic) NSString * startTime;//开始时间
@property (strong,nonatomic) NSString * endTime; //结束时间
@property (strong,nonatomic) NSString * lastWeekStartTime;//开始时间
@property (strong,nonatomic) NSString * lastWeekEndTime; //结束时间
@property (strong,nonatomic) IFSchedulAddButton * addSchedulPeppleBtn;
@property (strong,nonatomic) NSDate *titleDate;
@property (strong,nonatomic) NSMutableArray * theDateOfArray; //用来存放日期的数组
@property (strong,nonatomic)NSMutableArray * editDataSoureArray; //用来存放编辑或者修改后的
@property (assign,nonatomic) BOOL isClickLastWeekBtn; //用来记录是否点击了复制上周按钮
@property (assign,nonatomic) BOOL isChangeSchedul; //用来记录是否修改了当前周的班次
@property (strong,nonatomic) UILabel * progressHUDLabel;
@end
@implementation IFMySchedulingManagerVC

#pragma mark - Life cycle
- (void)loadView {
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.view = view;
    float offectX = view.frame.size.width/8.f;
    
    UILabel * weekLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, IFLY_kNavTopHeight, offectX + 3 ,  CGFloatIn375(45))];
    weekLabel.backgroundColor = SELECTED_TODAY_COLOR;
    weekLabel.text = @"星期";
    weekLabel.font = [UIFont systemFontOfSize:15];
    weekLabel.textAlignment = NSTextAlignmentCenter;
    weekLabel.textColor = [UIColor whiteColor];
    
    UIView * backView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(weekLabel.frame), offectX, 55)];
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    
    self.LastWeekCopyBtn = [[UIButton alloc] initWithFrame:CGRectMake(10 ,5, CGFloatIn320(30), CGFloatIn320(30))];
    self.LastWeekCopyBtn.layer.masksToBounds = YES;
    self.LastWeekCopyBtn.layer.cornerRadius = 3.f;
    self.LastWeekCopyBtn.titleLabel.numberOfLines=0;
    [self.LastWeekCopyBtn setTitle:@"复制\n上周" forState:UIControlStateNormal];
    self.LastWeekCopyBtn.backgroundColor = [UIColor colorWithHexString:@"cccccc"];
    self.LastWeekCopyBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.LastWeekCopyBtn addTarget:self action:@selector(copyLastClick:) forControlEvents:UIControlEventTouchUpInside];
    self.LastWeekCopyBtn.hidden = YES;
    
    [backView addSubview:self.LastWeekCopyBtn];
    [self.view bringSubviewToFront:self.LastWeekCopyBtn];
    
    self.gregorianCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    self.chineseCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(offectX, IFLY_kNavTopHeight, view.frame.size.width - offectX , CALENDAR_HEIGHT)];
    calendar.dataSource = self;
    calendar.delegate = self;
    calendar.backgroundColor = [UIColor whiteColor];
    calendar.appearance.caseOptions = FSCalendarCaseOptionsWeekdayUsesSingleUpperCase;
    self.calendar = calendar;
    
    calendar.appearance.titleTodayColor = SELECTED_TODAY_COLOR;//今天字体颜色
    calendar.appearance.subtitleTodayColor = SELECTED_TODAY_COLOR;//今天农历字体颜色
    calendar.appearance.todayColor = [UIColor whiteColor];//今天时间背景色
//    calendar.layer.borderColor = SELECTED_TODAY_COLOR.CGColor;
//    calendar.layer.borderWidth = 0;
    calendar.appearance.eventDefaultColor = SELECTED_EVENT_COLOR;//圆点颜色
    calendar.appearance.eventSelectionColor = SELECTED_EVENT_COLOR;//圆点颜色
    calendar.appearance.selectionColor = SELECTED_OTHERDAY_COLOR;//选中背景色
    
    
    calendar.appearance.todaySelectionColor = SELECTED_TODAY_COLOR;//今天选中时背景色
    calendar.appearance.weekdayTextColor = [UIColor whiteColor];
    calendar.firstWeekday = 2;
    calendar.headerHeight = 0;//头部高度
    calendar.weekdayHeight = CGFloatIn375(45);//weekView高度
    [calendar.calendarWeekdayView setBackgroundColor:SELECTED_TODAY_COLOR];//weekview背景色
    [calendar.calendarHeaderView setBackgroundColor:SELECTED_TODAY_COLOR];//头部背景色
    
    self.dateFormatter = [[NSDateFormatter alloc] init];
    self.dateFormatter.dateFormat = @"yyyy/MM/dd";
    [self.calendar selectDate:[NSDate date] scrollToDate:YES];
    self.lunarChars = @[@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",@"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",@"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十"];
    __weak typeof(self) weakSelf = self;
    EKEventStore *store = [[EKEventStore alloc] init];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if(granted) {
            NSDate* startDate = [NSDate dateWithTimeIntervalSinceNow:-365*24*60*60];//事件段，开始时间
            NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow:365*24*60*60];//结束时间，取中间
            NSPredicate *fetchCalendarEvents = [store predicateForEventsWithStartDate:startDate endDate:endDate calendars:nil];
            NSArray<EKEvent *> *eventList = [store eventsMatchingPredicate:fetchCalendarEvents];
            NSArray<EKEvent *> *events = [eventList filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(EKEvent * _Nullable event, NSDictionary<NSString *,id> * _Nullable bindings) {
                return event.calendar.subscribed;
            }]];
            weakSelf.events = events;
        }
    }];
    /* 暂时去掉下拉刷新 上拉加载更多
     self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headRefresh)];
     
     self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
     */
    [self setTitleWithDate:self.calendar.currentPage];

    // self.selectNumber = 0;
    [self.calendar setScope:FSCalendarScopeWeek animated:NO];
    
    [self.view addSubview:calendar];
    [self.view addSubview:weekLabel];
    [self.view addSubview:self.tableView];
 
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0,115 +  CGFloatIn375(45) - 0.2f, kScreenWidth, 0.5f)];
    lineView.backgroundColor = [UIColor colorWithHexString:@"DDDDDD"];
    [self.view addSubview:lineView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [Common saveImageDocuments:[Common drawRectangle:CGRectMake(0, 0,  kScreenWidth/8.f,  kScreenWidth/8.f) withRadius:3 AndwithLineWidth:0.01f AndwithLineColor:[UIColor colorWithHexString:@"d4d4d4"] AndwithFillColor:[UIColor colorWithHexString:@"f4f4f4"]] AndImageName:@"NoEditorPic"];
    [Common saveImageDocuments:[Common drawRectangle:CGRectMake(0, 0,  kScreenWidth/8.f,  kScreenWidth/8.f) withRadius:3 AndwithLineWidth:0.01f AndwithLineColor:[UIColor colorWithHexString:@"d4d4d4"] AndwithFillColor:[UIColor whiteColor]] AndImageName:@"EditorPic"];
    [Common saveImageDocuments:[Common drawRectangle:CGRectMake(0, 0,  kScreenWidth/8.f,  kScreenWidth/8.f) withRadius:3 AndwithLineWidth:0.01f AndwithLineColor:[UIColor colorWithHexString:@"feae7e"] AndwithFillColor:[UIColor whiteColor]] AndImageName:@"EditorSelectPic"];
    
    self.selectStateViewArray = [NSMutableArray arrayWithCapacity:0];
    self.selectLinedUpClassArray = [NSMutableArray arrayWithCapacity:0];
    self.dataSourArray = [NSMutableArray arrayWithCapacity:0];
    self.theDateOfArray = [NSMutableArray  arrayWithCapacity:0];
    self.view.backgroundColor = [UIColor whiteColor];
    self.pageNum = 1;
    [self creatbottomView];
    [self.view setBackgroundColor:[UIColor colorWithHexString:@"f5f5f9"]];
      MyNavbar * nav =  [[MyNavbar alloc] initWithTitle:@"" andController:self] ;
    [nav show];
    nav.backBlock = ^{
        if (self.addButton.selected) {
        [self creatActionSheetView];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    };
    [self.view addSubview:self.monthTitle];
    [self.view addSubview:self.addButton];
    [self.view addSubview:self.progressHUDLabel];
    [self.view bringSubviewToFront:self.progressHUDLabel];
    self.progressHUDLabel.hidden = YES;
    self.progressHUDLabel.alpha = 0.5f;
    [SVProgressHUD showWithStatus:@"加载中"];
}


- (void)creatbottomView {
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, SCHEDULE_BOTTOM_HEIGHT)];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomView];
    self.addSchedulBtn = [[IFSchedulAddButton alloc] initWithFrame:CGRectMake((kScreenWidth - SCHEDULE_BOTTOM_HEIGHT) - 10, 0,SCHEDULE_BOTTOM_HEIGHT,SCHEDULE_BOTTOM_HEIGHT)];
    [self.addSchedulBtn setImage:[UIImage imageNamed:@"scheduleImage.bundle/icon_scheduling_add"] forState:UIControlStateNormal];
    [self.addSchedulBtn setTitle:@"编辑班次" forState:UIControlStateNormal];
    self.addSchedulBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.addSchedulBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    // [self.bottomView addSubview:self.addSchedulBtn];
    [self.addSchedulBtn addTarget:self action:@selector(addScheduleClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.bottomTimeView];
    [self.bottomView addSubview:self.addSchedulBtn];
    [self requestDataList];
}

#pragma mark -----创建底部弹框
- (void)creatActionSheetView {
    WS(weakSelf)
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"排班已修改,是否保存" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.selectLinedUpClassArray removeAllObjects];
        [self.selectStateViewArray removeAllObjects];
        weakSelf.addButton.selected = NO;
        weakSelf.LastWeekCopyBtn.hidden = YES;
        [weakSelf.bottomTimeView.selectArray removeAllObjects];
        [weakSelf.bottomTimeView.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        weakSelf.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.calendar.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.calendar.frame));
        [UIView animateWithDuration:0.5f animations:^{
            weakSelf.bottomView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, SCHEDULE_BOTTOM_HEIGHT);
        }];
        weakSelf.tableView.tableFooterView.hidden = YES;
        for (IFSchedulDocModel * docModel in weakSelf.dataSourArray) {
            for (IFSchedulDocListModel * listModel in docModel.classArrangementList) {
                listModel.isSelect = NO;
            }
        }
        [self.tableView reloadData];
    }];
    UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.selectStateViewArray removeAllObjects];
        [self.selectLinedUpClassArray removeAllObjects];
        weakSelf.addButton.selected = NO;
        weakSelf.LastWeekCopyBtn.hidden = YES;
        [weakSelf.bottomTimeView.selectArray removeAllObjects];
        [weakSelf.bottomTimeView.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        weakSelf.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.calendar.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.calendar.frame));
        [UIView animateWithDuration:0.5f animations:^{
            weakSelf.bottomView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, SCHEDULE_BOTTOM_HEIGHT);
        }];
        self.tableView.tableFooterView.hidden = YES;
        for (IFSchedulDocModel * docModel in self.dataSourArray) {
            for (IFSchedulDocListModel * listModel in docModel.classArrangementList) {
                listModel.isSelect = NO;
             
                listModel.deptCode = [UserService share].currentAccount.selectedDeptCode;
                NSMutableDictionary * dic = listModel.mj_keyValues;
                [weakSelf.editDataSoureArray addObject:dic];
                
            }
        }
        [weakSelf creatAndModifyTheSchedulingRequest:weakSelf.editDataSoureArray];
        [weakSelf.tableView reloadData];
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [weakSelf presentViewController:alert animated:YES completion:nil];
}

- (void)headRefresh {
    self.pageNum = 1;
    [self getMySchedulingListRequest:YES];
    
}

- (void)loadMoreData {
    self.pageNum++;
    [self getMySchedulingListRequest:NO];
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
      [self addFirstComeGuide];
}

- (void)dealloc {
  //  [self removeObserver:self forKeyPath:@"selectNumber" context:nil];
    NSLog(@"%s",__FUNCTION__);
}

#pragma mark --- ZAddSchedulingClassDelegate 添加班次
- (void)saveSchedulingClassDidCompleteArray:(NSArray *)classArray {
    for (IFSchedulDocModel * docModel in self.dataSourArray) {
        for (IFSchedulDocListModel * listModel in docModel.classArrangementList) {
            listModel.isSelect = NO;
        }
    }
    [self.selectStateViewArray removeAllObjects];
    [self.selectLinedUpClassArray removeAllObjects];
    self.bottomTimeView.dataSourArray = [NSMutableArray arrayWithArray:classArray];
    [self.bottomTimeView.selectArray removeAllObjects];
    [self.bottomTimeView.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    [self.tableView reloadData];
    if (self.bottomTimeView.dataSourArray.count == 0) {
        self.addSchedulBtn.frame = CGRectMake((kScreenWidth - SCHEDULE_BOTTOM_HEIGHT)/2.f, 0,SCHEDULE_BOTTOM_HEIGHT,SCHEDULE_BOTTOM_HEIGHT);
    } else {
        self.addSchedulBtn.frame= CGRectMake((kScreenWidth - SCHEDULE_BOTTOM_HEIGHT) - 10, 0,SCHEDULE_BOTTOM_HEIGHT,SCHEDULE_BOTTOM_HEIGHT);
    }
    if (self.selectStateViewArray.count == 0 && self.selectLinedUpClassArray.count == 0) {
        self.bottomTimeView.isClickItem = NO;
    } else {
        self.bottomTimeView.isClickItem = YES;
    }
}

#pragma mark - <IFAddScheduingPersonDelegate> 添加人员
- (void)passValueForAddScheduingPersonAndArray:(NSMutableArray *)selectArray {
    [self.dataSourArray removeAllObjects];
    IFSchedulDocModel * selfListModel;
    NSMutableArray * dataSourTempArray = [NSMutableArray arrayWithCapacity:0];
    for (IFSchedulDocPersonModel * personModel in selectArray) {
        IFSchedulDocModel * listModel = [[IFSchedulDocModel alloc] init];
        listModel.docId = personModel.username;
        listModel.docName = personModel.realName;
        listModel.shouPin = personModel.shouPin;
        if (personModel.classArrangementList.count > 0) {
            listModel.classArrangementList = personModel.classArrangementList;
        } else {
            NSMutableArray * tempArray = [NSMutableArray arrayWithCapacity:0];
            for (int i = 0; i < WEEKS_COUNT; i++) {
                IFSchedulDocListModel * Model = [[IFSchedulDocListModel alloc] init];
                Model.deptCode = personModel.dptCode;
                Model.classTime = self.theDateOfArray[i];
                Model.docName = personModel.realName;
                Model.docId = personModel.username;
                Model.createId = [UserService share].currentAccount.selectedHosConfig.userInfo.userId;
                Model.classInfoIds = @"";
                Model.classNames = @"";
                Model.classColors = @"";
                Model.classArrangementId =@"";
                [tempArray addObject:Model];
                
            }
            listModel.classArrangementList = [NSArray arrayWithArray:tempArray];
        }
        if ([listModel.docId isEqualToString:[UserService share].currentAccount.selectedHosConfig.userInfo.userId]) {
            selfListModel = listModel;
           // [self.dataSourArray insertObject:listModel atIndex:0];
        } else {
            [dataSourTempArray addObject:listModel];
        }
    }
    self.dataSourArray = [NSMutableArray arrayWithArray:[self sortShouPinWithDataArray:[NSArray arrayWithArray:dataSourTempArray]]];
    if (selfListModel) {
     [self.dataSourArray insertObject:selfListModel atIndex:0];
    }
    [self.tableView reloadData];
}

#pragma mark - <UIGestureRecognizerDelegate>
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    BOOL shouldBegin = self.tableView.contentOffset.y <= -self.tableView.contentInset.top;
    if (shouldBegin) {
        CGPoint velocity = [self.scopeGesture velocityInView:self.view];
        switch (self.calendar.scope) {
            case FSCalendarScopeMonth:
                return velocity.y < 0;
            case FSCalendarScopeWeek:
                return velocity.y > 0;
        }
    }
    return shouldBegin;
}

#pragma mark - <FSCalendarDelegate>

- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date {
   
    return 0;
}

- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated {
  //  [self saveSelectedItem];
    [self getCurrentWeeksAllDates];
    [self getMySchedulingListRequest:YES];
    calendar.height = CGRectGetHeight(bounds);
    if (_addButton.selected) {
        self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.calendar.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.calendar.frame) - SCHEDULE_BOTTOM_HEIGHT);
    } else {
//        self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.calendar.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.calendar.frame) - (kScreenHeight - CGRectGetMinY(super.animationView.frame)));
         self.tableView.frame  = CGRectMake(0, CGRectGetMaxY(self.calendar.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.calendar.frame) );
    }
    [self.view layoutIfNeeded];
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
    NSLog(@"did select date %@",[self.dateFormatter stringFromDate:date]);
    NSMutableArray *selectedDates = [NSMutableArray arrayWithCapacity:calendar.selectedDates.count];
    [calendar.selectedDates enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [selectedDates addObject:[self.dateFormatter stringFromDate:obj]];
    }];
    NSLog(@"selected dates is %@",selectedDates);
    if (monthPosition == FSCalendarMonthPositionNext || monthPosition == FSCalendarMonthPositionPrevious) {
        [calendar setCurrentPage:date animated:YES];
    }
    [self setTitleWithDate:self.calendar.selectedDate];
}

- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date {
    EKEvent *event = [self eventsForDate:date].firstObject;
    if (event) {
        return event.title; // 春分、秋分、儿童节、植树节、国庆节、圣诞节...
    }
    NSInteger day = [_chineseCalendar component:NSCalendarUnitDay fromDate:date];
    return _lunarChars[day-1]; // 初一、初二、初三...
}

// 某个日期的所有事件
- (NSArray<EKEvent *> *)eventsForDate:(NSDate *)date {
    NSArray<EKEvent *> *filteredEvents = [self.events filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(EKEvent * _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        return [evaluatedObject.occurrenceDate isEqualToDate:date];
    }]];
    return filteredEvents;
}

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar {
    if (calendar.scope == FSCalendarScopeMonth) { //日历展开时候的状态
        [self setTitleWithDate:self.calendar.currentPage];
                if (![self equalDate:calendar.currentPage withOtherDate:calendar.selectedDate]) {
                [calendar selectDate:calendar.currentPage];
            }
    }
    else {
        [self setTitleWithDate:self.calendar.currentPage];
        NSInteger day = [Common numberOfDaysWithFromDate:self.calendar.currentPage toDate:self.calendar.selectedDate];
        if (day >= 0 && day <= 6) {
                 [self setTitleWithDate:self.calendar.selectedDate];
        } else {
              [self setTitleWithDate:self.calendar.currentPage];
        }
    }
    [self.bottomTimeView.selectArray removeAllObjects];
    [self.bottomTimeView.collectionView reloadData];
    if (self.isChangeSchedul && self.addButton.selected ) {
        NSMutableArray * cacheArray = [NSMutableArray arrayWithCapacity:0];
        for (IFSchedulDocModel * docModel in self.dataSourArray) {
            for (IFSchedulDocListModel * listModel in docModel.classArrangementList) {
                listModel.deptCode = [UserService share].currentAccount.selectedDeptCode;
                NSMutableDictionary * dic = listModel.mj_keyValues;
                [cacheArray addObject:dic];
            }
        }
        self.isChangeSchedul = NO;
        [self creatAndModifyTheSchedulingRequest:cacheArray];
    }
    [self getCurrentWeeksAllDates];
    self.pageNum = 1;
    [self getMySchedulingListRequest:YES];
}

#pragma mark ---  获取当前周的所有时间
- (void)getCurrentWeeksAllDates {
    self.pageNum = 1;
    [self.theDateOfArray removeAllObjects];
    [self.dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSInteger distance = 6; // 加的天数
    for (int i = 0; i <= distance; i ++) {
        NSDate *newDate = [self.calendar.currentPage dateByAddingTimeInterval:24 * 60 * 60  * i];
        NSString * dateString = [self.dateFormatter stringFromDate:newDate];
        [self.theDateOfArray addObject:dateString];
        
    }
    NSDate *newDate = [self.calendar.currentPage dateByAddingTimeInterval:24 * 60 * 60  * distance];
    self.startTime = [self.dateFormatter stringFromDate:self.calendar.currentPage];
    self.endTime = [self.dateFormatter stringFromDate:newDate];
    self.lastWeekStartTime = [self.dateFormatter stringFromDate:[self.calendar.currentPage dateByAddingTimeInterval:24 * 60 * 60  * (-(distance + 1))]];
    self.lastWeekEndTime = [self.dateFormatter stringFromDate:[self.calendar.currentPage dateByAddingTimeInterval:24 * 60 * 60  * (-1)]];
    NSLog(@"start %@ end %@ ,lastTime %@ fff %@",self.startTime,self.endTime,self.lastWeekStartTime,self.lastWeekEndTime);
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSourArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   IFMySchedulCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(IFMySchedulCell.class) forIndexPath:indexPath];
    cell.delegate = self;
    cell.isEdit = self.addButton.selected;
    [cell configForDocTorModel:self.dataSourArray[indexPath.row] AndIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return TABLEVIEWROWHEIGHT;
}

#pragma mark - Date相关
- (BOOL)equalDate:(NSDate *)date withOtherDate:(NSDate *)otherDate {
    
    return [[self formatUserDefaultWithDate:date] isEqualToString:[self formatUserDefaultWithDate:otherDate]];
}

- (NSString *)formatUserDefaultWithDate:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy/MM";
    return [formatter stringFromDate:date];
}

#pragma mark - Target actions
- (void)copyLastClick:(UIButton *)sender {
    WS(weakSelf)
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否复制上周所有排班信息" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
       
    }];
    UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
         weakSelf.isChangeSchedul = YES;
        [[IFly_APIManager shareManager] api_getMySchedulingListWithDeptCode:/*DEPT_ID*/nil StartTime:weakSelf.lastWeekStartTime EndTime:weakSelf.lastWeekEndTime PageNum:[@(weakSelf.pageNum) stringValue] PageSize:@"100" backBlock:^(BackDataVO *data, NSError *error) {
            if (data) {
                if ([data.s isEqualToString:@"1"]) {
                    [weakSelf.dataSourArray removeAllObjects];
                    NSArray *userVO = [IFSchedulDocModel mj_objectArrayWithKeyValuesArray:data.r];
                    if (userVO.count > 0) {
                        for (IFSchedulDocModel * docModel in userVO) {
                            docModel.classArrangementList = [IFSchedulDocListModel mj_objectArrayWithKeyValuesArray:docModel.classArrangementList];
                            for (int i = 0; i < docModel.classArrangementList.count; i ++) {
                                IFSchedulDocListModel * listModel = docModel.classArrangementList[i];
                                listModel.classTime = weakSelf.theDateOfArray[i];
                            }
                            
                            [weakSelf.dataSourArray addObject:docModel];
                        }
                    } else {
                        //[self getLastWeekClassArrangementInformationRequest];
                    }
                    [weakSelf.tableView reloadData];
                    
                } else {
                    //  [self getLastWeekClassArrangementInformationRequest];
                    if (![data.ec containsString:@"00034"]) {
                        [weakSelf.dataSourArray removeAllObjects];
                        [weakSelf.tableView reloadData];
                        //[SVProgressHUD showTextHUD:data.em];
                    }
                    
                }
            }
        }];
        
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)addScheduleClick:(UIButton *)sender {
    ZAddSchedulingViewController * addScheduVC = [[ZAddSchedulingViewController alloc] init];
    addScheduVC.delegate = self;
    [self.navigationController pushViewController:addScheduVC animated:YES];
}

- (void)addPersonClick:(UIButton *)sender {
    IFAddScheduingPersonVC * personVC = [[IFAddScheduingPersonVC alloc] init];
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
    for (IFSchedulDocModel * docModel in self.dataSourArray) {
        IFSchedulDocPersonModel * personModel = [[IFSchedulDocPersonModel alloc] init];
        personModel.username = docModel.docId;
        personModel.realName = docModel.docName;
        personModel.shouPin = docModel.shouPin;
        personModel.classArrangementList = docModel.classArrangementList;
        [array addObject:personModel];
    }
    personVC.selectArray = [NSMutableArray arrayWithArray:array];
    personVC.delegate = self;
    [self.navigationController pushViewController:personVC animated:YES];
}

- (void)addClick:(UIButton *)sender {
    [self addFirstEditGuide];
    sender.selected = !(sender.selected);
    if (sender.selected) { //处于编辑状态
        self.LastWeekCopyBtn.hidden = NO;
        [self.editDataSoureArray removeAllObjects];
        self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.calendar.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.calendar.frame) - SCHEDULE_BOTTOM_HEIGHT);
        [UIView animateWithDuration:0.5f animations:^{
            self.bottomView.frame = CGRectMake(0,kScreenHeight - SCHEDULE_BOTTOM_HEIGHT,kScreenWidth, SCHEDULE_BOTTOM_HEIGHT);
            
        }];
        self.tableView.tableFooterView.hidden = NO;
        
    } else {
        [self.selectStateViewArray removeAllObjects];
        [self.selectLinedUpClassArray removeAllObjects];
        self.LastWeekCopyBtn.hidden = YES;
        [self.bottomTimeView.selectArray removeAllObjects];
        [self.bottomTimeView.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.calendar.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.calendar.frame));
        [UIView animateWithDuration:0.5f animations:^{
            self.bottomView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, SCHEDULE_BOTTOM_HEIGHT);
        }];
        self.tableView.tableFooterView.hidden = YES;
        for (IFSchedulDocModel * docModel in self.dataSourArray) {
            for (IFSchedulDocListModel * listModel in docModel.classArrangementList) {
                listModel.isSelect = NO;
                listModel.deptCode = [UserService share].currentAccount.selectedDeptCode;
                NSMutableDictionary * dic = listModel.mj_keyValues;
                [self.editDataSoureArray addObject:dic];
                
            }
        }
        [self creatAndModifyTheSchedulingRequest:self.editDataSoureArray];
    }
    [self.tableView reloadData];
}

#pragma mark  --- 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.calendar.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.calendar.frame))];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass(IFMySchedulCell.class) bundle:nil] forCellReuseIdentifier:NSStringFromClass(IFMySchedulCell.class)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.allowsMultipleSelectionDuringEditing = YES;
        [_tableView setBackgroundColor:[UIColor colorWithHexString:@"f5f5f9"]];
        UIView * tableFootView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,kScreenWidth, 60)];;
        tableFootView.backgroundColor = [UIColor whiteColor];
        self.addSchedulPeppleBtn = [[IFSchedulAddButton alloc] initWithFrame:CGRectMake((kScreenWidth - SCHEDULE_BOTTOM_HEIGHT)/2.f, 0,SCHEDULE_BOTTOM_HEIGHT,SCHEDULE_BOTTOM_HEIGHT)];
        [self.addSchedulPeppleBtn setImage:[UIImage imageNamed:@"scheduleImage.bundle／icon_scheduling_addperson"] forState:UIControlStateNormal];
        [self.addSchedulPeppleBtn setTitle:@"编辑人员" forState:UIControlStateNormal];
        self.addSchedulPeppleBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.addSchedulPeppleBtn addTarget:self action:@selector(addPersonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.addSchedulPeppleBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [tableFootView addSubview:self.addSchedulPeppleBtn];
        self.tableView.tableFooterView = tableFootView;
        self.tableView.tableFooterView.hidden = YES;
    }
    return _tableView;
}

- (IFSchedulTimeView *)bottomTimeView {
    if (!_bottomTimeView) {
        _bottomTimeView = [[IFSchedulTimeView alloc] initWithFrame:CGRectMake(0,0 , kScreenWidth - CGRectGetWidth(self.addSchedulBtn.frame) - 10, SCHEDULE_BOTTOM_HEIGHT)];
        
        _bottomTimeView.delegate = self;
    }
    return _bottomTimeView;
    
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)editDataSoureArray {
    if (!_editDataSoureArray) {
       _editDataSoureArray  = [NSMutableArray array];
    }
    return _editDataSoureArray;
}

- (MainTopButton *)monthTitle {
    if (!_monthTitle) {
        _monthTitle = [[MainTopButton alloc] initWithFrame:CGRectMake(50, 20, kScreenWidth - 100, IFLY_kNavBarHeight)];
        _monthTitle.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        _monthTitle.titleLabel.font = IFLY_SYS_FONT(18);
        [_monthTitle setTitleColor:[UIColor colorWithHexString:@"232323"] forState:UIControlStateNormal];
        _monthTitle.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        [_monthTitle addTarget:self action:@selector(deptClick:) forControlEvents:UIControlEventTouchUpInside];
        [_monthTitle setImage:IMAGE(@"patient_down") forState:UIControlStateNormal];
    }
    return _monthTitle;
}

- (UILabel *)progressHUDLabel {
    if (!_progressHUDLabel) {
        //115 +  CGFloatIn375(45) - 0.2f
        _progressHUDLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,CGFloatIn375(45) + 116, kScreenWidth, 30)];
        _progressHUDLabel.backgroundColor = SELECTED_TODAY_COLOR;
        _progressHUDLabel.text = @"排班信息已经保存";
        _progressHUDLabel.font = [UIFont systemFontOfSize:13.f];
        _progressHUDLabel.textAlignment = NSTextAlignmentCenter;
        _progressHUDLabel.textColor = [UIColor whiteColor];
    }
    return _progressHUDLabel;
}

- (IFLYBackButton *)addButton {
    if (!_addButton) {
        _addButton = [[IFLYBackButton alloc] initWithFrame:CGRectMake(kScreenWidth - IFLY_kNavBarHeight - 10, 20 + 13, 60, 18)];
        _addButton.titleLabel.font = [UIFont systemFontOfSize:16.f];
        [_addButton setTitleColor:MAIN_COLOR forState:UIControlStateNormal];
        [_addButton setTitle:@"编辑" forState:UIControlStateNormal];
        [_addButton setTitle:@"完成" forState:UIControlStateSelected];
        [_addButton addTarget:self
                       action:@selector(addClick:)
             forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _addButton;
}

- (SBPickerSelector *)datePicker {
    if (!_datePicker) {
        _datePicker = [SBPickerSelector picker];
        _datePicker.pickerType = SBPickerSelectorTypeDate;
        _datePicker.datePickerType = SBPickerSelectorDateTypeOnlyMonthAndYear;
        _datePicker.doneButtonTitle = @"确定";
        _datePicker.cancelButtonTitle = @"取消";
        _datePicker.delegate = self;
    }
    return _datePicker;
}

-(void) pickerSelector:(SBPickerSelector *)selector dateSelected:(NSDate *)date {
    [self.calendar setCurrentPage:date];
    [self setTitleWithDate:date];
}

- (void)deptClick:(UIButton *)sender {
    self.datePicker.defaultDate = self.titleDate;
    [self.datePicker showPickerOver:self];
}

- (void)setTitleWithDate:(NSDate *)date {
    self.titleDate = date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy年MM月";
    [self.monthTitle setTitle:[formatter stringFromDate:date] forState:UIControlStateNormal];
}


#pragma -mark 网络请求
- (void)requestDataList {
    [IFly_APIManager shareManager].ip_business = @"https://yyscloud-dev.iflyhealth.com:6008/YYS-BusinessServer/";
    [[IFly_APIManager shareManager] defineNetSystemParamsWithWGLat:0 andWgLon:0 andToken:[UserService share].currentAccount.token andPhone:[UserService share].currentAccount.userphone];
    
    [[IFly_APIManager shareManager] api_getClassInfoWithDeptCode:[UserService share].currentAccount.selectedDeptCode andBackBlock:^(BackDataVO *data, NSError *error) {
        if ([data.s isEqualToString:@"1"]) {
            self.bottomTimeView.dataSourArray = [ZSchedulingTypeModel mj_objectArrayWithKeyValuesArray:data.r];
            [self.bottomTimeView.collectionView reloadData];
            if (self.bottomTimeView.dataSourArray.count == 0) {
                self.addSchedulBtn.frame = CGRectMake((kScreenWidth - SCHEDULE_BOTTOM_HEIGHT)/2.f, 0,SCHEDULE_BOTTOM_HEIGHT,SCHEDULE_BOTTOM_HEIGHT);
            } else {
                self.addSchedulBtn.frame= CGRectMake((kScreenWidth - SCHEDULE_BOTTOM_HEIGHT) - 10, 0,SCHEDULE_BOTTOM_HEIGHT,SCHEDULE_BOTTOM_HEIGHT);
            }
        } else {
            if (self.bottomTimeView.dataSourArray.count == 0) {
                self.addSchedulBtn.frame = CGRectMake((kScreenWidth - SCHEDULE_BOTTOM_HEIGHT)/2.f, 0,SCHEDULE_BOTTOM_HEIGHT,SCHEDULE_BOTTOM_HEIGHT);
            } else {
                self.addSchedulBtn.frame= CGRectMake((kScreenWidth - SCHEDULE_BOTTOM_HEIGHT) - 10, 0,SCHEDULE_BOTTOM_HEIGHT,SCHEDULE_BOTTOM_HEIGHT);
            }
            
        }
    }];
}

- (void)creatAndModifyTheSchedulingRequest:(NSMutableArray *)array {
    [IFly_APIManager shareManager].ip_business = @"https://yyscloud-dev.iflyhealth.com:6008/YYS-BusinessServer/";
    [[IFly_APIManager shareManager] defineNetSystemParamsWithWGLat:0 andWgLon:0 andToken:[UserService share].currentAccount.token andPhone:[UserService share].currentAccount.userphone];
    
    // NSLog(@"当前科室 %@",[IFlyUserDefault objectForKey:DEPT_ID]);
    [[IFly_APIManager shareManager] api_createClassArrangementWithWithListArray:array DeptCode:[UserService share].currentAccount.selectedDeptCode StartTime:self.startTime EndTime:self.endTime andBackBlock:^(BackDataVO *data, NSError *error) {
        if (data) {
            if ([data.s isEqualToString:@"1"]) {
                //排班信息已经保存
                if (self.addButton.selected) {
                    [UIView animateWithDuration:0.5f animations:^{
                        self.progressHUDLabel.alpha = 1;
                        self.progressHUDLabel.hidden = NO;
                    } completion:^(BOOL finished) {
                        self.progressHUDLabel.alpha = 0.5;
                        self.progressHUDLabel.hidden = YES;
                        
                    }];
                } else {
                    [SVProgressHUD showTextHUD:@"排班信息已经保存"];
                }
                
            }else {
                if (![data.ec containsString:@"00034"]) {
                    [SVProgressHUD showTextHUD:data.em];
                }
            }
        }
    }];
}

- (void)getLastWeekClassArrangementInformationRequest {
    [IFly_APIManager shareManager].ip_business = @"https://yyscloud-dev.iflyhealth.com:6008/YYS-BusinessServer/";
    [[IFly_APIManager shareManager] defineNetSystemParamsWithWGLat:0 andWgLon:0 andToken:[UserService share].currentAccount.token andPhone:[UserService share].currentAccount.userphone];
    
    [[IFly_APIManager shareManager] api_getLastWeekClassArrangementWithDeptCode:[UserService share].currentAccount.selectedDeptCode ReadyClassTime:self.startTime andBackBlock:^(BackDataVO *data, NSError *error) {
        if (data) {
            if ([data.s isEqualToString:@"1"]) {
                NSArray *userVO = [IFSchedulDepartmentModel mj_objectArrayWithKeyValuesArray:data.r];
                IFSchedulDepartmentModel * departmentModelModel = [userVO firstObject];
                departmentModelModel.dptCode = [UserService share].currentAccount.selectedDeptCode;
                NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dic in departmentModelModel.userContacts) {
                    IFSchedulDocPersonModel *model = [IFSchedulDocPersonModel mj_objectWithKeyValues:dic];
                    model.dptCode = departmentModelModel.dptCode;
                    [array addObject:model];
                }
                NSMutableArray * tempDataSourArr = [NSMutableArray arrayWithCapacity:0];
                for (IFSchedulDocPersonModel * personModel in array) {
                    IFSchedulDocModel * listModel = [[IFSchedulDocModel alloc] init];
                    // listModel.deptCode = personModel.dptCode;
                    listModel.docId = personModel.username;
                    listModel.docName = personModel.realName;
                    listModel.shouPin = personModel.shouPin;
                    if (personModel.classArrangementList.count > 0) {
                        listModel.classArrangementList = personModel.classArrangementList;
                    } else {
                        NSMutableArray * tempArray = [NSMutableArray arrayWithCapacity:0];
                        for (int i = 0; i < WEEKS_COUNT; i++) {
                            IFSchedulDocListModel * Model = [[IFSchedulDocListModel alloc] init];
                            Model.deptCode = personModel.dptCode;
                            Model.classTime = self.theDateOfArray[i];
                            Model.docName = personModel.realName;
                            Model.docId = personModel.username;
                            Model.createId = [UserService share].currentAccount.selectedHosConfig.userInfo.userId;// [IFlyUserDefault objectForKey:DOC_ID];
                            Model.classInfoIds = @"";
                            Model.classNames = @"";
                            Model.classColors = @"";
                            Model.classArrangementId =@"";
                            [tempArray addObject:Model];
                        }
                        listModel.classArrangementList = [NSArray arrayWithArray:tempArray];
                    }
                    [tempDataSourArr addObject:listModel];
                }
                self.isChangeSchedul= YES;
                self.dataSourArray = [NSMutableArray arrayWithArray:tempDataSourArr];
                [self.tableView reloadData];
            } else {
                if (![data.ec containsString:@"00034"]) {
                    // [SVProgressHUD showTextHUD:data.em];
                }
            }
        }
    }];
}

- (void)getMySchedulingListRequest:(BOOL)flag {
    
    // [IFly_APIManager shareManager].ip_business = @"https://yyscloud-dev.iflyhealth.com:5038/DocServer_yys_test/";
//https://yyscloud-dev.iflyhealth.com:6008/YYS-BusinessServer/service/sygong/getClassArrangement
    
    [IFly_APIManager shareManager].ip_business = @"https://yyscloud-dev.iflyhealth.com:6008/YYS-BusinessServer/";
    [[IFly_APIManager shareManager] defineNetSystemParamsWithWGLat:0 andWgLon:0 andToken:[UserService share].currentAccount.token andPhone:[UserService share].currentAccount.userphone];
    
    [[IFly_APIManager shareManager] api_getMySchedulingListWithDeptCode:[UserService share].currentAccount.selectedDeptCode StartTime:self.startTime EndTime:self.endTime PageNum:[@(self.pageNum) stringValue] PageSize:@"100" backBlock:^(BackDataVO *data, NSError *error) {
        [SVProgressHUD dismiss];
        if (data) {
            if ([data.s isEqualToString:@"1"]) {
                if (flag) {
                    [self.dataSourArray removeAllObjects];
                }
                NSArray *userVO = [IFSchedulDocModel mj_objectArrayWithKeyValuesArray:data.r];
                if (userVO.count > 0) {
                    for (IFSchedulDocModel * docModel in userVO) {
                        docModel.classArrangementList = [IFSchedulDocListModel mj_objectArrayWithKeyValuesArray:docModel.classArrangementList];
                        if (docModel.classArrangementList.count < WEEKS_COUNT) {
                            NSMutableArray * tempArray = [NSMutableArray arrayWithArray:docModel.classArrangementList];
                            NSMutableArray * dataArr = [NSMutableArray arrayWithArray:self.theDateOfArray];
                            for (IFSchedulDocListModel * listModel in tempArray) {
                                [dataArr removeObject:listModel.classTime];
                            }
                            for (int i = 0; i < WEEKS_COUNT -  (int)docModel.classArrangementList.count; i++) {
                                IFSchedulDocListModel * Model = [[IFSchedulDocListModel alloc] init];
                                Model.deptCode = [UserService share].currentAccount.selectedDeptCode;
                                Model.classTime = dataArr[i];
                                Model.docName = docModel.docName;
                                Model.shoupin = docModel.shouPin;
                                Model.docId = docModel.docId;
                                Model.createId = [UserService share].currentAccount.selectedHosConfig.userInfo.userId;;
                                Model.classInfoIds = @"";
                                Model.classNames = @"";
                                Model.classColors = @"";
                                Model.classArrangementId =@"";
                                [tempArray addObject:Model];
                            }
                            docModel.classArrangementList = [NSArray arrayWithArray:tempArray];
                            for (int j = 0; j < self.theDateOfArray.count; j++) {
                                NSString * dataString = self.theDateOfArray[j];
                                for (IFSchedulDocListModel * doclistModel in docModel.classArrangementList) {
                                    if ([doclistModel.classTime isEqualToString:dataString]) {
                                        [tempArray exchangeObjectAtIndex:j withObjectAtIndex:[tempArray indexOfObject:doclistModel]];
                                    }
                                }
                            }
                            docModel.classArrangementList = [NSArray arrayWithArray:tempArray];
                        }
                        [self.dataSourArray addObject:docModel];
                    }
                    [self.tableView.mj_header endRefreshing];
                    [self.tableView.mj_footer endRefreshing];
                    
                } else {
                    [self.tableView.mj_header endRefreshing];
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    if(self.addButton.selected) {
                        [self getLastWeekClassArrangementInformationRequest];
                    }
                }
                [self.tableView reloadData];
                
            } else {
                if (flag) {
                    [self.dataSourArray removeAllObjects];
                    [self.tableView reloadData];
                }
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                if(self.addButton.selected) {
                    [self getLastWeekClassArrangementInformationRequest];
                }
                if (![data.ec containsString:@"00034"]) {
                   // [SVProgressHUD showTextHUD:data.em];
                }
                
            }
        }
    }];
}

#pragma mark ------- IFmyschedullDelegate
- (void)btnSelectClick:(UIButton *)sender {
    self.isChangeSchedul = YES;
    IFScheduStateView * stateView = (IFScheduStateView *)sender.superview;
    stateView.isSelect = !stateView.isSelect;
    IFMySchedulCell * myCell = (IFMySchedulCell *)stateView.superview;
    NSIndexPath * indexPath = [self.tableView indexPathForCell:myCell];
    IFSchedulDocModel * docModel = self.dataSourArray[indexPath.row];
    IFSchedulDocListModel * docListModel = docModel.classArrangementList[stateView.viewIndex - 1];
    if (stateView.upLabel.text.length > 0
        || stateView.downLabel.text.length > 0 || stateView.bigLabel.text.length > 0) {
        if (self.selectStateViewArray.count > 0) {
            for (IFSchedulDocListModel * model in self.selectStateViewArray) {
                model.isSelect = NO;
            }
        }
        [self.selectStateViewArray removeAllObjects];
        IFSchedulDocListModel * view = [self.selectLinedUpClassArray firstObject];
        [self.selectLinedUpClassArray removeAllObjects];
        [self.selectLinedUpClassArray addObject:docListModel];
        if(view) {
            if ([view isEqual:docListModel]) {
                if (!view.isSelect) {
                    view.isSelect = YES;
                }
            } else {
                view.isSelect = NO;
                docListModel.isSelect = YES;
            }
        } else {
            docListModel.isSelect = YES;
        }
        if (stateView.scheduleType == SchedulingViewSpaceType) {
            [self.bottomTimeView reloatData:nil];
        } else if (stateView.scheduleType == SchedulingViewOneLinesType) {
            [self.bottomTimeView reloatData:[NSMutableArray arrayWithObjects:stateView.bigLabel.schedulingTypeModel,nil]];
        } else if (stateView.scheduleType == SchedulingViewTwoLinesType) {
            [self.bottomTimeView reloatData:[NSMutableArray arrayWithObjects:stateView.upLabel.schedulingTypeModel,stateView.downLabel.schedulingTypeModel,nil]];
        }
    } else {
        if (self.selectLinedUpClassArray.count > 0) {
            IFSchedulDocListModel * view = [self.selectLinedUpClassArray firstObject];
            view.isSelect = NO;
            [self.selectLinedUpClassArray removeAllObjects];
        }
        for (IFSchedulDocListModel * staView in self.selectStateViewArray) {
            if (staView.scheduleType != SchedulingViewSpaceType) {
                staView.isSelect = NO;
            } else {
                if (self.isClickSchedul) {
                    staView.isSelect = NO;
                } else {
                    staView.isSelect = YES;
                }
            }
        }
        self.isClickSchedul = NO;
        if (docListModel.isSelect) {
            docListModel.isSelect = NO;
            [self.selectStateViewArray removeObject:docListModel];
            
        } else {
            docListModel.isSelect = YES;
            [self.selectStateViewArray addObject:docListModel];
        }
        NSMutableArray * array = [NSMutableArray arrayWithArray:self.selectStateViewArray];
        for (IFSchedulDocListModel * sView in array) {
            if (!sView.isSelect) {
                [self.selectStateViewArray removeObject:sView];
            }
        }
        [self.bottomTimeView reloatData:nil];
    }
    [self.tableView reloadData];
    if (self.selectStateViewArray.count == 0 && self.selectLinedUpClassArray.count == 0) {
        self.bottomTimeView.isClickItem = NO;
    } else {
        self.bottomTimeView.isClickItem = YES;
    }
}


#pragma mark - ifSchedViewDelegate
- (void)selectSchedulingTimeClick:(NSString *)SchedulingTimeString SelectNameCollectionCellModel:(ZSchedulingTypeModel *)cellModel {
    self.isClickSchedul = YES;
    self.isChangeSchedul = YES;
    if (self.selectLinedUpClassArray.count > 0) {
        IFSchedulDocListModel * view = [self.selectLinedUpClassArray firstObject];
        [self UsedToLayoutViewAccordingToTheSchedulingTimeString:SchedulingTimeString AndSelectNameCollectionCellModel:cellModel AndIFScheduStateView:view];
        
    } else {
        for (IFSchedulDocListModel * listModel in self.selectStateViewArray) {
            [self UsedToLayoutViewAccordingToTheSchedulingTimeString:SchedulingTimeString AndSelectNameCollectionCellModel:cellModel AndIFScheduStateView:listModel];
            
        }
    }
}

- (void)UsedToLayoutViewAccordingToTheSchedulingTimeString:(NSString *)SchedulingTimeString AndSelectNameCollectionCellModel:(ZSchedulingTypeModel *)Model AndIFScheduStateView:(IFSchedulDocListModel *)listModel {
    NSArray * classNameArr,*classColorArr,*classinfoIdArr;
    if (listModel.classColors.length > 0) {
        classColorArr = [listModel.classColors componentsSeparatedByString:@","];
    }
    if (listModel.classInfoIds.length > 0) {
        classinfoIdArr = [listModel.classInfoIds componentsSeparatedByString:@","];
    }
    if (listModel.classNames.length > 0) {
        classNameArr = [listModel.classNames componentsSeparatedByString:@","];
    }
    if (SchedulingTimeString.length > 0) {
        if (classNameArr.count == 0) {
            listModel.classNames = [NSString stringWithFormat:@"%@",SchedulingTimeString];
            listModel.classInfoIds = [NSString stringWithFormat:@"%@",Model.classInfoId];
            listModel.classColors = Model.color;
            listModel.scheduleType = SchedulingViewSpaceType;
        } else if (classNameArr.count == 1) {
            NSMutableArray * titleArray= [NSMutableArray arrayWithCapacity:0];
            for (ZSchedulingTypeModel * typeModel in self.bottomTimeView.dataSourArray) {
                [titleArray addObject:typeModel.classInfoId]; //classInfoId 替换成 classname
            }
            if ([titleArray containsObject:[classinfoIdArr firstObject]]) {
                listModel.classNames = [NSString stringWithFormat:@"%@,%@",[classNameArr firstObject],SchedulingTimeString];
                listModel.classInfoIds = [NSString stringWithFormat:@"%@,%@",[classinfoIdArr firstObject],Model.classInfoId];
                listModel.classColors = [NSString stringWithFormat:@"%@,%@",[classColorArr firstObject],Model.color] ;
                listModel.scheduleType = SchedulingViewTwoLinesType;
                
            } else {
                listModel.classNames = [NSString stringWithFormat:@"%@",SchedulingTimeString];
                listModel.classInfoIds = [NSString stringWithFormat:@"%@",Model.classInfoId];
                listModel.classColors = [NSString stringWithFormat:@"%@",Model.color] ;
                listModel.scheduleType = SchedulingViewOneLinesType;
            }
            
        } else if (classNameArr.count == 2) {
            NSMutableArray * titleArray= [NSMutableArray arrayWithCapacity:0];
            for (ZSchedulingTypeModel * typeModel in self.bottomTimeView.dataSourArray) {
                [titleArray addObject:typeModel.classInfoId]; //classInfoId 替换成 classname
            }
            if ([titleArray containsObject:[classinfoIdArr firstObject]]) { ////classInfoId 替换成 classname
                listModel.classNames = [NSString stringWithFormat:@"%@,%@",[classNameArr firstObject] ,SchedulingTimeString];
                listModel.classInfoIds = [NSString stringWithFormat:@"%@,%@",[classinfoIdArr firstObject],Model.classInfoId];
                listModel.classColors = [NSString stringWithFormat:@"%@,%@",[classColorArr firstObject],Model.color];
                listModel.scheduleType = SchedulingViewTwoLinesType;
            } else if([titleArray containsObject:[classinfoIdArr lastObject]]) {
                listModel.classNames = [NSString stringWithFormat:@"%@,%@",SchedulingTimeString,[classNameArr lastObject]];
                listModel.classInfoIds = [NSString stringWithFormat:@"%@,%@",Model.classInfoId,[classinfoIdArr lastObject]];
                listModel.classColors = [NSString stringWithFormat:@"%@,%@",Model.color,[classColorArr lastObject]];
                listModel.scheduleType = SchedulingViewTwoLinesType;
            } else {
                listModel.classNames = [NSString stringWithFormat:@"%@",SchedulingTimeString];
                listModel.classInfoIds = [NSString stringWithFormat:@"%@",Model.classInfoId];
                listModel.classColors = [NSString stringWithFormat:@"%@",Model.color];
                listModel.scheduleType = SchedulingViewOneLinesType;
            }
        }
    } else {
        if (listModel.scheduleType == SchedulingViewTwoLinesType) {
            if (self.bottomTimeView.selectArray.count == 0) {
                listModel.classNames = @"";
                listModel.classInfoIds = @"";
                listModel.classColors = @"";
                listModel.scheduleType = SchedulingViewSpaceType;
            } else {
                if ([[classinfoIdArr firstObject] isEqualToString:Model.classInfoId]) {
                    listModel.classNames = [NSString stringWithFormat:@"%@",[classNameArr lastObject]];
                    listModel.classInfoIds = [NSString stringWithFormat:@"%@",[classinfoIdArr lastObject]];
                    listModel.classColors = [NSString stringWithFormat:@"%@",[classColorArr lastObject]];
                    listModel.scheduleType = SchedulingViewOneLinesType;
                } else {
                    listModel.classNames = [NSString stringWithFormat:@"%@",[classNameArr firstObject]];
                    listModel.classInfoIds = [NSString stringWithFormat:@"%@",[classinfoIdArr firstObject]];
                    listModel.classColors = [NSString stringWithFormat:@"%@",[classColorArr firstObject]];
                    listModel.scheduleType = SchedulingViewOneLinesType;
                }
            }
        } else if(listModel.scheduleType == SchedulingViewOneLinesType) {
            listModel.classNames = @"";
            listModel.classInfoIds = @"";
            listModel.classColors = @"";
            listModel.scheduleType = SchedulingViewSpaceType;
        }
    }
    [self.tableView reloadData];
}

- (ZSchedulingTypeModel *)getZSchedulingTypeModel:(NSString *)schedulText {
    ZSchedulingTypeModel * model;
    for (ZSchedulingTypeModel * typeModel in self.bottomTimeView.dataSourArray) {
        if ([typeModel.classInfoId isEqualToString:schedulText]) {
            
            model = typeModel;
        }
        
    }
    return model;
}

#pragma mark ---  排序
- (NSArray *)sortShouPinWithDataArray:(NSArray *)array {
    NSMutableArray *sortArray = [NSMutableArray array];
    NSMutableDictionary *sortDictory = [NSMutableDictionary dictionary];
    NSMutableArray * indexTitles = [NSMutableArray arrayWithCapacity:0];
    for (IFSchedulDocModel *caseTemp in array) {
        NSMutableArray *tempArr = [sortDictory valueForKey:caseTemp.shouPin];
        if (tempArr) {
            [tempArr addObject:caseTemp];
        } else {
            NSMutableArray *newTempArr = [NSMutableArray array];
            [newTempArr addObject:caseTemp];
            [sortDictory setValue:newTempArr forKey:caseTemp.shouPin];
            [indexTitles addObject:caseTemp.shouPin];
        }
    }
    indexTitles = [Common sortFirstStrWithArray:indexTitles];
    NSString *shoupin = [indexTitles firstObject];
    if ([shoupin isEqualToString:@"#"]) {
        [indexTitles removeObjectAtIndex:0];
        [indexTitles addObject:@"#"];
    }
    for (NSString *shoupin in indexTitles) {
        [sortArray addObjectsFromArray:[sortDictory valueForKey:shoupin]];
    }
    
    return sortArray;
}

#pragma mark - 第一次进入
- (void)addFirstComeGuide {
    [Common addGuideWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"首次进入排班表" ofType:@"png"]] vc:self guideDefaultString:@"首次进入排班表" selector:@selector(guideOver:)];
}

- (void)addFirstEditGuide {
    [Common addGuideWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"首次编辑排班表" ofType:@"png"]] vc:self guideDefaultString:@"首次编辑排班表" selector:@selector(guideOver:)];
}

- (void)guideOver:(UITapGestureRecognizer *)sender {
    [sender.view removeFromSuperview];
}


@end
